package com.intellekt.ecert.connection.action;

import static org.apache.commons.lang3.StringUtils.isAlphanumeric;
import static org.apache.commons.lang3.StringUtils.isAlphanumericSpace;
import static org.apache.commons.lang3.StringUtils.isBlank;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.intellekt.ecert.connection.service.ConnectionsService;
import com.intellekt.ecert.connection.vo.ConnectionVO;
import com.intellekt.ecert.domain.SuperAction;

public class ConnectionsAsyncAction extends SuperAction {

	/**
     * 
     */
	private static final long serialVersionUID = -6536964772985551843L;

	private static final Logger log = Logger.getLogger(ConnectionsAsyncAction.class);

	private static final String DIV_CONNECTION = "div.idConnection";
	private static final String DIV_COUNTRY = "div.idCountry";
	private static final String DIV_USERNAME = "div.username";
	private static final String DIV_PASSWORD = "div.password";
	private static final String DIV_URL = "div.url";
	
	
	private String jsonrecords;
	private ConnectionVO connection;
	
	
	@Autowired
	private ConnectionsService service;

	public String execute() throws Exception {

		if (log.isInfoEnabled()) {
			log.info("execute...");
		}

		JSONObject messages = new JSONObject();
		JSONArray divs = new JSONArray();
		JSONArray alerts = new JSONArray();
		boolean success = true;

		try {

			Map<Object, Object> resultSet = new HashMap<Object, Object>();
			List<Map<Object, Object>> mapResult = new ArrayList<Map<Object, Object>>();

			List<ConnectionVO> lista = service.getConnections();

			for (ConnectionVO vo : lista) {
				Map<Object, Object> map = new HashMap<Object, Object>();


				mapResult.add(map);
			}
			resultSet.put("Result", mapResult);
			messages.put("ResultSet", resultSet);

		} catch (Exception e) {
			log.error("error", e);
			success = false;
			messages.put(JSON_EXCEPTION, e.toString());
		} finally {
			messages.put(JSON_DIVS, divs);
			messages.put(JSON_ALERTS, alerts);
			messages.put(JSON_SUCCESS, success);
			if (log.isDebugEnabled()) {
				log.debug(messages.toString(1));
			}
			streamIt(messages);
		}

		return STREAM;

	}

	
	public String validar() throws Exception {
		if (log.isInfoEnabled()) {
			log.info("validar...");
			log.info("validar..."+connection.toString());
		}
		JSONObject messages = new JSONObject();
		JSONArray divs = new JSONArray();
		JSONArray alerts = new JSONArray();
		boolean success = true;
		String msgError = null;

		try {
			if (connection.isNuevo()) {
				/**
				 * Validar el username del usuario cuando sea nuevo
				 */
				String idConnection = connection.getIdConnection();
				msgError = "";
				if (isBlank(idConnection)) {
					success = false;
					msgError = "Introduzca un ID para la conexion";
				}
				if (!isAlphanumeric(idConnection)) {
					success = false;
					msgError = "No se permiten caracteres especiales";
				}
				if (service.connectionExist(idConnection.toUpperCase())) {
					msgError = "Ya existe una conexion con ese ID " + idConnection;
					success = false;
				}
				divs.add(getDivYMensaje(DIV_CONNECTION, msgError));
			}
			/**
			 * Validar el nombre del usuario
			 */
			boolean errorNombre = false;
			String nombre = connection.getUsername();
			msgError = "";
			if (isBlank(nombre)) {
				errorNombre = true;
				msgError = this.getText("segusuarios.nombre.blank");
			} else if (nombre.trim().length() > 100) {
				errorNombre = true;
				msgError = this.getText("segusuarios.nombre.longitud");
			}
			if (!isAlphanumericSpace(nombre)) {
				errorNombre = true;
				msgError = this.getText("segusuarios.username.incorrecto");
			}
			if (errorNombre) {
				success = false;
			}
			divs.add(getDivYMensaje(DIV_USERNAME, msgError));


			boolean errorPassword = false;
			String password = connection.getPassword();
			msgError = "";
			if (isBlank(password)) {
				errorPassword = true;
				msgError = this.getText("segusuarios.nombre.blank");
			} else if (nombre.trim().length() > 100) {
				errorPassword = true;
				msgError = this.getText("segusuarios.nombre.longitud");
			}
			if (!isAlphanumericSpace(password)) {
				errorPassword = true;
				msgError = this.getText("segusuarios.username.incorrecto");
			}
			if (errorPassword) {
				success = false;
			}
			divs.add(getDivYMensaje(DIV_PASSWORD, msgError));
			
			
			boolean errorUrl = false;
			String url = connection.getUrl();
			msgError = "";
			if (isBlank(url)) {
				errorUrl = true;
				msgError = "Introduzca la URL de conexion";
			}
			if (errorUrl) {
				success = false;
			}
			divs.add(getDivYMensaje(DIV_URL, msgError));

			boolean errorPais = false;
			String country = connection.getIdCountry();
			msgError = "";
			if (isBlank(country)) {
				errorPais = true;
				msgError = this.getText("segusuarios.mail.blank");
			}
			if (errorPais) {
				success = false;
			}
			divs.add(getDivYMensaje(DIV_COUNTRY, msgError));


		} catch (Exception e) {
			log.error("error", e);
			success = false;
			messages.put(JSON_EXCEPTION, e.toString());
		} finally {
			messages.put(JSON_DIVS, divs);
			messages.put(JSON_ALERTS, alerts);
			messages.put(JSON_SUCCESS, success);
			if (log.isDebugEnabled()) {
				log.debug(messages.toString(1));
			}
			streamIt(messages);
		}
		return STREAM;
	}
	



	public ConnectionVO getConnection() {
		return connection;
	}
	public void setConnection(ConnectionVO connection) {
		this.connection = connection;
	}
	public void setJsonrecords(String jsonrecords) {
		this.jsonrecords = jsonrecords;
	}
	public String getJsonrecords() {
		return jsonrecords;
	}

}
